package com.pjmike.netty.protocol.message.encoder;

import com.pjmike.netty.protocol.message.command.Command;
import com.pjmike.netty.utils.Crc32Util;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @Author bj
 * @Description //输出报文统一加上CRC32校验和BW
 * @Date 10:22 2021/1/11
 * @Param
 * @return
 **/
public class Crc32Encoder extends MessageToByteEncoder<ByteBuf> {

    @Override
    protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
        byte[] bytes = new byte[msg.readableBytes()];
        msg.readBytes(bytes);
        //添加报文CRC32校验位
        long crc32 = Crc32Util.getMessageCrc32ByBytes(bytes,0);
        out.writeBytes(bytes);
        out.writeInt((int)crc32);
        //添加报文尾
        short bw = Command.BW;
        out.writeByte((byte)bw);
    }
}
